#include "MdlFileLoader.h"
#include <iostream>
#include <fstream>

bool LoadMdlFile( std::string& filename, MdlFile& mdlFile )
{
	int length = 0;
	std::ifstream file(filename);

	if(!file.is_open())
		return false;

	unsigned int count;
	
	file >> mdlFile.modelName;
	
	file >>	mdlFile.skeletonName;

	file >>	count;
	mdlFile.meshes.resize(count);

	for (std::vector<MdlFileMesh>::iterator it = mdlFile.meshes.begin(), end = mdlFile.meshes.end(); it != end; ++it )
	{
		for (int i = 0; i < 4; ++i)
			file >> it->material.ambient[i];
		
		for (int i = 0; i < 4; ++i)
			file >> it->material.diffuse[i];
		
		for (int i = 0; i < 4; ++i)
			file >> it->material.specular[i];
		
		for (int i = 0; i < 4; ++i)
			file >> it->material.emmisive[i];
		
		file >> it->material.shininess;
		
		file >>	it->material.shaderName;
		
		file >>	count;
		it->uniforms.resize(count);
		
		for (std::vector<MdlFileUniform>::iterator uniform = it->uniforms.begin(); uniform != it->uniforms.end(); ++uniform)
		{
			file >>	uniform->uniformName;
			file >>	uniform->numberOfElements;
			file >>	uniform->uniformType;
		}
		
		unsigned int verticeSize, verticeOffset, verticeType, totalSize = 0;
		
		file >>	count;
		it->parameters.reserve(count);
		for (unsigned int j = 0; j < count; ++j)
		{
			file >>	verticeOffset;
			file >>	verticeSize;
			file >>	verticeType;
			if (verticeType ==  0x84CA)
			{
				totalSize += verticeSize;
			} else 
			{
				totalSize += verticeSize * 4;
			}
			it->parameters.push_back(Type(verticeOffset, verticeSize, verticeType));
		}
		file >>	it->vertexCount;
		it->vertexData.resize(it->vertexCount * totalSize);
		unsigned char *pVBuf = &(it->vertexData[0]);

		for (unsigned int j = 0; j < it->vertexCount; ++j)
		{
			for (Type::Vector_t::iterator vertice = it->parameters.begin(); vertice != it->parameters.end(); ++vertice)
			{
				if (vertice->m_parameter ==  0x84CA)
				{
					for (unsigned int k = 0; k < vertice->m_size; ++k)
					{
						file >>	*pVBuf;
						pVBuf += sizeof(unsigned char);
					}
				} else 
				{
					for (unsigned int k = 0; k < vertice->m_size; ++k)
					{
						float value;
						if (!file.eof() && !file.fail() && !file.bad())
						{
							file >>	value;
							*(float*)pVBuf = value;
							pVBuf += sizeof(float);
						}
					}
				}
			}
		}
	}
	file.close();
	return true;
}
